package _8_Gorm框架老郭

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

//安装：go get gorm.io/gorm
//https://gorm.io/zh_CN/docs/

type Product struct {
	gorm.Model //模型
	Code       string
	Price      uint
}

func main() {
	//"用户名:密码@tcp(127.0.0.1:3306)/数据库名?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := "root:123456@tcp(127.0.0.1:3306)/golang_db?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("failed to connect darabase")
	}

	//迁移 schema,创建表
	db.AutoMigrate(&Product{})

	//create,创建数据
	db.Create(&Product{Code: "D42", Price: 100})

	//read
	var product Product
	db.First(&product, 1) //根据整形主键查找
	fmt.Println(product)

	db.First(&product, "Code = ? ", "D42") //查找code字段值为d42的记录

	// Update - 将 product 的 price 更新为 200
	db.Model(&product).Update("Price", 200)
	// Update - 更新多个字段
	db.Model(&product).Updates(Product{Price: 200, Code: "F42"}) // 仅更新非零值字段
	db.Model(&product).Updates(map[string]interface{}{"Price": 200, "Code": "F42"})

	// Delete - 删除 product
	db.Delete(&product, 1)
}
